package com.jshoperxms.controller.mall.backstage.storeinfo;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.GoodsCommentEnums;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.GoodsTypeT;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.entity.StoreInfoT;
import com.jshoperxms.service.StoreInfoTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by sdywcd on 16/10/21.
 * Des:
 */
@Controller
@RequestMapping("/mall/storeinfo")
public class StoreInfoTController extends BaseTController implements IBaseCtrl<StoreInfoT> {

    @Resource
    private StoreInfoTService storeInfoTService;

    //数据形式
    private Map<String, Object> responsedata = new HashMap<>();

    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody StoreInfoT rq) {
        if(StringUtils.isNotBlank(rq.getStorename())){
            if(checkDuplicates(rq.getStorename())){
                StoreInfoT bean=new StoreInfoT();
                bean.setId(this.serial.Serialid(SerialKeys.STOREINFOT));
                bean.setAddress(rq.getAddress());
                Map<String,String>map= BaseTools.parseImg(rq.getMainimg());
                bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                Map<String,String>map1= BaseTools.parseImg(rq.getCompanyimg());
                bean.setCompanyimg(map1.get(TagWords.NORMALFILEPATH));
                bean.setCompanyname(rq.getCompanyname());
                bean.setDes(rq.getDes());
                bean.setCreatetime(DateTools.getSystemTimeBi());
                bean.setCreatorid(BaseTools.getAdminCreateId());
                bean.setIdcard(rq.getIdcard());
                bean.setIsreviewed(rq.getIsreviewed());
                bean.setMaster(rq.getMaster());
                bean.setEmail(rq.getEmail());
                bean.setMobile(rq.getMobile());
                bean.setStatus(rq.getStatus());
                bean.setStorename(rq.getStorename());
                bean.setTelno(rq.getTelno());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(1);
                this.storeInfoTService.save(bean);
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG, WarnWrods.ERROR_HAVE_KEY);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody StoreInfoT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            StoreInfoT bean=this.storeInfoTService.findByPK(StoreInfoT.class,rq.getId());
            if(bean!=null){
                ImgFileBean ifb=new ImgFileBean();
                ifb.setNormalfilepath(bean.getMainimg());
                ifb.setCompressfilepath(bean.getSmainimg());
                ifb.setBasepath(StaticKey.EMPTY);
                ImgFileBean ifbs=new ImgFileBean();
                ifbs.setNormalfilepath(bean.getCompanyimg());
                ifbs.setBasepath(StaticKey.EMPTY);
                responsedata.put(TagWords.IFB,ifb);
                responsedata.put(TagWords.IFBS,ifbs);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody StoreInfoT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(), TagWords.SPLITDOT);
            for(String s:ids){
                StoreInfoT bean=this.storeInfoTService.findByPK(StoreInfoT.class, s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.storeInfoTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody StoreInfoT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
                    StoreInfoT bean = this.storeInfoTService.findByPK(StoreInfoT.class, rq.getId());
                    if (bean != null) {
                        bean.setAddress(rq.getAddress());
                        Map<String, String> map = BaseTools.parseImg(rq.getMainimg());
                        bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                        bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                        Map<String, String> map1 = BaseTools.parseImg(rq.getCompanyimg());
                        bean.setCompanyimg(map1.get(TagWords.NORMALFILEPATH));
                        bean.setCompanyname(rq.getCompanyname());
                        bean.setDes(rq.getDes());
                        bean.setIdcard(rq.getIdcard());
                        bean.setIsreviewed(rq.getIsreviewed());
                        bean.setMaster(rq.getMaster());
                        bean.setMobile(rq.getMobile());
                        bean.setStatus(rq.getStatus());
                        bean.setEmail(rq.getEmail());
                        bean.setStorename(rq.getStorename());
                        bean.setTelno(rq.getTelno());
                        bean.setUpdatetime(DateTools.getSystemTimeBi());
                        bean.setVersiont(bean.getVersiont()+1);
                        this.storeInfoTService.update(bean);
                        responsedata.put(TagWords.SUCCESS, true);
                        responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);

                }
        }

        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }

    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("storename",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("storename",search,MatchMode.ANYWHERE));
            }
            int records=this.storeInfoTService.count(StoreInfoT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<StoreInfoT> list = this.storeInfoTService.findByCriteriaByPage(
                    StoreInfoT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);
        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion;
        Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        Criterion criterion2=Restrictions.like("storename",search,MatchMode.ANYWHERE);
        criterion=Restrictions.and(criterion1).add(criterion2);
        int records=this.storeInfoTService.count(StoreInfoT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<StoreInfoT> list = this.storeInfoTService.findByCriteriaByPage(
                StoreInfoT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.storeInfoTService.count(StoreInfoT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("storename",ordervalue,ordertype);
        List<StoreInfoT> list = this.storeInfoTService.findByCriteriaByPage(
                StoreInfoT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<StoreInfoT> list) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (Iterator<StoreInfoT> it = list.iterator(); it.hasNext(); ) {
            StoreInfoT bean = it.next();
            //如果缩略图没有就使用原图
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String, Object> cellMap = new HashMap<String, Object>();
            cellMap.put("id", bean.getId());
            cellMap.put("smainimg",bean.getMainimg());
            cellMap.put("storename", bean.getStorename());
            cellMap.put("master", bean.getMaster());
            cellMap.put("telno", bean.getTelno());
            cellMap.put("isreviewed", GoodsCommentEnums.CommentReviewed.getName(bean.getIsreviewed()));
            cellMap.put("companyname", bean.getCompanyname());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        if(StringUtils.isBlank(str)){
            return false;
        }
        Criterion criterion= Restrictions.eq("storename",str);
        StoreInfoT bean=this.storeInfoTService.findOneByCriteria(StoreInfoT.class, criterion);
        if(bean!=null){
            return false;
        }
        return true;
    }
}
